/**
 * 类型断言
 */
/*------------------------------------------------------------*/
// function func(val: string | number): number {
//   if (val.length) {
//     return val.length
//   } else {
//     return val.toString().length
//   }
// }
// val是联合类型(访问联合类型值的属性时, 这个属性必须是所有可能类型的共有属性, 而length不是共有属性, 爆错)


// 类型断言
function func1(val: string | number): number {
  if ((<string>val).length) {
    return (<string>val).length
  } else {
    return val.toString().length
  }
}
function func2(val: string | number): number {
  if ((val as string).length) {
    return (val as string).length
  } else {
    return val.toString().length
  }
}

/*------------------------------------------------------------*/
/**  as const **/ 
function asConst() {
  let a:string = 'abc'
  let b = (firstname: string, lastname: string): string => firstname + lastname 
  return [a, b]
}
let [p, q] = asConst()
// console.log(q('a', 'b'))
// 上述代码会直接编译失败，原因是系统认为变量q的类型是string | ((firstname: string, lastname: string) => string)，编译器并不能认定q是一个函数。
// 
function asConst1() {
  let a:string = 'abc'
  let b = (firstname: string, lastname: string): string => firstname + lastname 
  return [a, b] as const
}
let [p1, q1] = asConst1()
console.log(q1('a', 'b'))


function asConst2() {
  let a:string = 'abc'
  let b = (firstname: string, lastname: string): string => firstname + lastname
  return [a, b] as [typeof a, typeof b]
}
let [p2, q2] = asConst1()
console.log(q2('a', 'b'))
/*------------------------------------------------------------*/
